// fetch poems/*.json

const WRONG_LIMIT = 3;

const app = document.getElementById("app");

let currentIndex = 0;
let continuousWrongCount = 0;
start();

injectStyle(`
.poem-item-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}
.poem-item {
  background-color: #f0f0f0;
  padding: 10px;
  cursor: pointer;

  &.right {
    background-color: #000;
    color: #fff;
  }
  &.wrong {
    background-color: #000;
    color: red;
  }
  &.shaking {
    animation: shaking 0.5s ease-in-out;
  }
  &.shining {
    animation: shining 0.5s ease-in-out;
  }
  &.badge {
    position: relative;
    &::after {
      content: attr(data-mapping);
      position: absolute;
      top: 0;
      left: 0;
      background-color: red;
      color: blue;
      padding: 2px 4px;
      border-radius: 4px;
      font-size: 12px;
    }
  }
}

@keyframes shaking {
  0% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-5px);
  }
  50% {
    transform: translateX(5px);
  }
  75% {
    transform: translateX(-5px);
  }
  100% {
    transform: translateX(0);
  }
}

@keyframes shining {
  0% {
    background-color: #f0f0f0;
    color: #FF0;
    scale: 1;
  }
  50% {
    background-color: #fff;
    color: #FFA500;
    scale: 1.2;
  }
  100% {
    background-color: #f0f0f0;
    color: #FF0;
    scale: 1;
  }
}
`);

/**
 * Inject style into the document head.
 * @param {string} style - The style string to inject.
 */
function injectStyle(style) {
  const styleElement = document.createElement("style");
  styleElement.textContent = style;
  document.head.appendChild(styleElement);
}

/**
 * Start the poem game.
 */
async function start() {
  currentIndex = 0;
  continuousWrongCount = 0;
  const poem = await fetch("./poems/1.json");
  const poemJson = await poem.json();

  const poemContent = renderPoem(poemJson, 4, 5);
  app.appendChild(poemContent);

  hydratePoemItems(poemJson);
}

/**
 * Render poem content to the DOM.
 * @param {Object} poemJson - The poem JSON object.
 * @param {number} row - The number of rows in the poem.
 * @param {number} col - The number of columns in the poem.
 */
function renderPoem(poemJson, row, col) {
  const poemContent = document.createElement("div");
  poemContent.className = "poem-content";
  for (let i = 0; i < row; i++) {
    const itemRow = document.createElement("div");
    itemRow.className = "poem-item-row";
    for (let j = 0; j < col; j++) {
      const index = i * col + j;
      const item = document.createElement("div");
      item.className = "poem-item";
      item.textContent = poemJson.content[index];
      item.dataset.mapping = poemJson.mappings[index];
      item.dataset.row = i;
      item.dataset.col = j;
      itemRow.appendChild(item);
    }
    poemContent.appendChild(itemRow);
  }

  return poemContent;
}

/**
 * Add click event listener to each poem item.
 */
function hydratePoemItems(poemJson) {
  document.querySelectorAll(`.poem-item`).forEach((item) => {
    item.addEventListener("click", (e) => {
      if (!item.dataset.mapping) {
        console.log("something wrong, no data-mapping");
        return;
      }
      if (item.classList.contains("right")) {
        console.log("already right");
        return;
      }
      if (item.classList.contains("wrong")) {
        console.log("already wrong");
        return;
      }

      if (+item.dataset.mapping == currentIndex) {
        document.querySelectorAll(`.poem-item`).forEach((item) => {
          item.classList.remove("wrong");
        });
        e.target.classList.add("right", "badge");
        continuousWrongCount = 0;
        currentIndex++;
        if (currentIndex >= poemJson.content.length) {
          donePoem();
          return;
        }
      } else {
        e.target.classList.add("wrong");
        e.target.addEventListener(
          "animationend",
          () => {
            console.log("animationend", continuousWrongCount);
            if (continuousWrongCount >= WRONG_LIMIT) {
              showTips();
            }
          },
          { once: true }
        );
        shakeItem(e.target.dataset.mapping);

        continuousWrongCount++;
      }
    });
  });
}

/**
 * Show tips for the current index.
 */
function showTips() {
  shineItem(currentIndex);
}

/**
 * Shake the poem item with the given index.
 * @param {number} index - The index of the poem item to shake.
 */
function shakeItem(index) {
  const item = document.querySelector(`.poem-item[data-mapping="${index}"]`);
  item.classList.remove("shaking");
  item.classList.add("shaking");
  item.addEventListener(
    "animationend",
    () => {
      item.classList.remove("shaking");
    },
    { once: true }
  );
}

/**
 * Shine the poem item with the given index.
 * @param {number} index - The index of the poem item to shine.
 */
function shineItem(index) {
  const item = document.querySelector(`.poem-item[data-mapping="${index}"]`);
  item.classList.remove("shining");
  item.classList.add("shining");
  item.addEventListener(
    "animationend",
    () => {
      item.classList.remove("shining");
    },
    { once: true }
  );
}

/**
 * Done the poem game.
 */
function donePoem() {
  console.log("YOU WIN!");
}
